package io.wdb.modules.generator.generator.service.impl.client;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;

import io.wdb.common.utils.HttpClientUtil;
import io.wdb.common.utils.PageHelperUtil;
import io.wdb.common.utils.Query;
import io.wdb.modules.generator.generator.dao.AccountCashDao;
import io.wdb.modules.generator.generator.dao.AccountCashLogDao;
import io.wdb.modules.generator.generator.dao.OrderTransDao;
import io.wdb.modules.generator.generator.dao.UserChargeLogDao;
import io.wdb.modules.generator.generator.dao.UserInfoDao;
import io.wdb.modules.generator.generator.entity.AccountCashEntity;
import io.wdb.modules.generator.generator.entity.AccountCashLogEntity;
import io.wdb.modules.generator.generator.entity.UserChargeLogEntity;
import io.wdb.modules.generator.generator.entity.UserInfoEntity;
import io.wdb.modules.generator.generator.entity.customer.AccountCashLogCustomer;
import io.wdb.modules.generator.generator.entity.customer.UserInfoEntityCustomer;
import io.wdb.modules.generator.generator.entity.web.BaseResponse;
import io.wdb.modules.generator.generator.entity.web.ResponseEnum;
import io.wdb.modules.generator.generator.entity.web.WebResponse;
import io.wdb.modules.generator.generator.service.client.ClientCapitalService;

@Service
public class ClientCapitalServiceImpl implements ClientCapitalService{

	@Value("${wdb007.refundurl}")
	private String refundUrl;
	
	@Autowired
	private AccountCashDao accountCashDao;
	
	@Autowired
	private AccountCashLogDao accountCashLogDao;
	
	@Autowired
	private OrderTransDao orderTransDao;
	
	@Autowired
	private UserInfoDao userInfoDao;
	
	@Autowired
	private UserChargeLogDao userChargeLogDao;
	@Override
	public List<UserInfoEntityCustomer> queryList(Query query) {
		if(query.get("refundStartTime")!=null&&!"".equals(query.get("refundStartTime").toString().trim())) {
			query.put("auditStatus", 6);
		}
		if(query.get("refundEndTime")!=null&&!"".equals(query.get("refundEndTime").toString().trim())) {
			query.put("auditStatus", 6);
		}
		/*if(query.get("payStartTime")!=null&&!"".equals(query.get("payStartTime").toString().trim())) {
			query.put("auditStatus", 2);
		}
		if(query.get("payEndTime")!=null&&!"".equals(query.get("payEndTime").toString().trim())) {
			query.put("auditStatus", 2);
		}*/
		
		List<UserInfoEntityCustomer> customers = userInfoDao.queryCapitalList(query);
		for(UserInfoEntityCustomer infoEntityCustomer:customers) {
			if(!(infoEntityCustomer.getAuditStatus()==7||infoEntityCustomer.getAuditStatus()==6)) {
				infoEntityCustomer.setModifyTime(null);
			}
			/*if(infoEntityCustomer.getDepositAmount()==null||"0.00".equals(infoEntityCustomer.getDepositAmount().toString())) {
				//查询用户退款流水
				UserChargeLogEntity chargeLogEntity = userChargeLogDao.getUserRefundLog(infoEntityCustomer.getId());
				if(chargeLogEntity==null) {
					infoEntityCustomer.setAuditStatus(6);//新注册
				}
			}*/
		}
		return customers;
	}

	@Override
	public int queryTotal(Query query) {
		return userInfoDao.queryCapitalListTotal(query);
	}

	@Override
	public List<AccountCashLogCustomer> queryRecord(Query query) {
		List<AccountCashLogCustomer> customers = accountCashLogDao.queryRecord(query);
		for(AccountCashLogCustomer customer:customers) {
			if(customer.getOperType()==null) {
				if(customer.getChangeAmount()==null) {
					customer.setChargeAmountCus("-0");
				}else {
					customer.setChargeAmountCus("-"+customer.getChangeAmount().toString());
				}
				if(customer.getChargeType()==null) {
					customer.setChargeStyleCus("4");//余额支付
					customer.setChargeTypeCus("2");//借阅费
				}
			} else if(customer.getOperType()==10) {
				customer.setChargeAmountCus("+"+customer.getChangeAmount().toString());
				if(customer.getChargeType()==10) {
					customer.setChargeStyleCus("1");//微信支付
					customer.setChargeTypeCus("3");//充值
				}else if(customer.getChargeType()==20) {
					customer.setChargeStyleCus("2");//支付宝支付
					customer.setChargeTypeCus("3");//充值
				}else if(customer.getChargeType()==30) {
					customer.setChargeStyleCus("3");//人工充值
					customer.setChargeTypeCus("4");//活动充值
				}else if(customer.getChargeType()==60) {
					customer.setChargeStyleCus("7");//充值券
					customer.setChargeTypeCus("6");//充值券
				}else if(customer.getChargeType()==70) {
					customer.setChargeStyleCus("8");//VIP充值赠送
					customer.setChargeTypeCus("7");//VIP充值赠送
				}else if(customer.getChargeType()==80) {
					customer.setChargeStyleCus("9");//邀请赠送
					customer.setChargeTypeCus("8");//邀请赠送
				}else if(customer.getChargeType()==90) {
					customer.setChargeStyleCus("10");//活动赠送
					customer.setChargeTypeCus("9");//活动赠送
				}
			}else if(customer.getOperType()==20) {
				customer.setChargeAmountCus("-"+customer.getChangeAmount().toString());
				if(customer.getChargeType()==50) {
					customer.setChargeStyleCus("4");//余额支付
					customer.setChargeTypeCus("2");//借阅费
					//Integer bookCount=orderTransDao.getBookCountByOrderId(customer.getOrderId()+"");
					//customer.setBookCount(bookCount);
				}else if(customer.getChargeType()==30) {
					customer.setChargeStyleCus("3");//人工充值
					customer.setChargeTypeCus("4");//活动充值
				}
			}else if(customer.getOperType()==30) {
				customer.setChargeAmountCus("-"+customer.getChangeAmount().toString());
				if(customer.getChargeType()==10) {
					customer.setChargeStyleCus("5");//微信退款
					customer.setChargeTypeCus("5");//退还押金
				}else if(customer.getChargeType()==20) {
					customer.setChargeStyleCus("6");//支付宝退款
					customer.setChargeTypeCus("5");//退还押金
				}
			}
			customer.setId(customer.getId());
			customer.setCreateTime(customer.getCreateTime());
		}
		return customers;
	}

	@Override
	public int queryTotalRecord(Query query) {
		return accountCashLogDao.queryTotalRecord(query);
	}

	@Override
	public Map<String, BigDecimal> getCash(Long id) {
		BigDecimal incomeCount = accountCashLogDao.getIncomeCount(id);
		BigDecimal expendCount = accountCashLogDao.getExpendCount(id);
		Map<String,BigDecimal> map = new HashMap<String,BigDecimal>();
		map.put("incomeCount", incomeCount);
		map.put("expendCount", expendCount);
		return map;
	}

	@Override
	public int addDeposit(AccountCashEntity accountCashEntity) {
		AccountCashEntity cashEntityDB = accountCashDao.queryObjectByUserId(accountCashEntity.getUserId());
		//有余额的时候对余额进行加和
		if(accountCashEntity.getCashAmount()!=null&&!"".equals(accountCashEntity.getCashAmount().toString())) {
			BigDecimal finalCashAmount = accountCashEntity.getCashAmount().add(cashEntityDB.getCashAmount());
			accountCashEntity.setCashAmount(finalCashAmount);
		}
		return accountCashDao.updateByUserId(accountCashEntity);
	}

	@Override
	public int applyForRefund(UserInfoEntity infoEntity) {
		//查询用户当前是否存在押金
		AccountCashEntity accountCashEntity = accountCashDao.queryObjectByUserId(infoEntity.getId());
		if(accountCashEntity==null) {
			return 1;//用户无押金
		}else {
			if(accountCashEntity.getStatus()!=10) {
				return 2;//用户押金被冻结
			}
		}
		//更改押金标识
		//用户不存在实际充值记录
		UserChargeLogEntity chargeLogEntity = userChargeLogDao.queryObjectByUserId(infoEntity.getId());
		if(chargeLogEntity==null||chargeLogEntity.getTradeNo()==null) {
			return 3;//用户无实际充值记录
		}
		chargeLogEntity.setAuditStatus("1");
		userChargeLogDao.update(chargeLogEntity);
		return 0;//申请退款成功
	}

	@Override
	public WebResponse auditRefundDeposit(UserInfoEntity infoEntity) {
		WebResponse webResponse = new WebResponse();
		try {
			UserChargeLogEntity chargeLogEntity = userChargeLogDao.queryAuditRefundLog(infoEntity);
			chargeLogEntity.setAuditStatus("3");
			userChargeLogDao.update(chargeLogEntity);
			webResponse.setCode(ResponseEnum.AUDIT_DEPOSIT_REFUND.getCode());
			webResponse.setMessage(ResponseEnum.AUDIT_DEPOSIT_REFUND.getMessage());
			return webResponse;
		} catch (Exception e) {
			
		}
		return null;
	}

	@Override
	public WebResponse operateRefundDeposit(UserInfoEntity infoEntity) {
		WebResponse webResponse = new WebResponse();
		UserChargeLogEntity chargeLogEntity = userChargeLogDao.queryOperateRefundLog(infoEntity);
		try {
		// 调用API退款接口
		// 使用Http请求调用注册功能
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		BasicNameValuePair outTradeNoParam = new BasicNameValuePair("outTradeNo", chargeLogEntity.getOutTradeNo());
		params.add(outTradeNoParam);
			//TODO
			String body = HttpClientUtil.getPostBodyDataNameValuePair(refundUrl+"/charge/refundByOutTradeNo", params);
			System.out.println(body);
			BaseResponse baseResponse=JSON.parseObject(body,BaseResponse.class);
			if(baseResponse.getResult()==1) {
				webResponse.setCode(ResponseEnum.OPERATE_DEPOSIT_SUCCESS.getCode());
				webResponse.setMessage(ResponseEnum.OPERATE_DEPOSIT_SUCCESS.getMessage());
			}else {
				webResponse.setCode(ResponseEnum.OPERATE_DEPOSIT_FAIL.getCode());
				webResponse.setMessage(baseResponse.getMessage());
			}
		} catch (IOException e) {
			webResponse.setCode(ResponseEnum.OPERATE_DEPOSIT_FAIL.getCode());
			webResponse.setMessage(ResponseEnum.OPERATE_DEPOSIT_FAIL.getMessage());
			return webResponse;
		}
		return webResponse;
	}

	@Override
	public int addDepositAmount(AccountCashEntity accountCashEntity) {
		
		AccountCashEntity accountCashEntityDb =accountCashDao.queryObjectByUserId(accountCashEntity.getUserId());
		accountCashEntityDb.setDepositAmount(accountCashEntity.getDepositAmount());
		accountCashEntityDb.setModifyTime(new Date());
		accountCashDao.update(accountCashEntityDb);
		// 入现金账户变动表
		AccountCashLogEntity accountCashLogEntity = new AccountCashLogEntity();
		accountCashLogEntity.setAccountCashId(accountCashEntityDb.getId());
		accountCashLogEntity.setChangeAmount(accountCashEntity.getDepositAmount());
		accountCashLogEntity.setChargeType(30);
		accountCashLogEntity.setCreateTime(new Date());
		accountCashLogEntity.setModifyTime(new Date());
		accountCashLogEntity.setOperType(10);
		accountCashLogEntity.setOrderId(1L);
		accountCashLogDao.save(accountCashLogEntity);
		
		//记录充值流水，以便后期查看此充值流水
		UserChargeLogEntity chargeLogEntity = new UserChargeLogEntity();
		chargeLogEntity.setAuditStatus(null);
		chargeLogEntity.setChannel(null);
		chargeLogEntity.setChargeAmount(accountCashEntity.getDepositAmount());
		chargeLogEntity.setCreateTime(new Date());
		chargeLogEntity.setModifyTime(new Date());
		chargeLogEntity.setTradeStatus(2);
		chargeLogEntity.setUserId(accountCashEntity.getUserId());
		userChargeLogDao.save(chargeLogEntity);
		return 0;
	}

	@Override
	public int addCashAmount(AccountCashEntity accountCashEntity) {
		AccountCashEntity accountCashEntityDb = accountCashDao.queryObjectByUserId(accountCashEntity.getUserId());
		BigDecimal dbCashAmount = accountCashEntityDb.getCashAmount();
		BigDecimal addCashAmount = accountCashEntity.getCashAmount();
		BigDecimal currentCashAmount = dbCashAmount.add(addCashAmount);
		accountCashEntityDb.setCashAmount(currentCashAmount);
		accountCashEntityDb.setModifyTime(new Date());
		accountCashDao.update(accountCashEntityDb);

		// 入现金账户变动表
		AccountCashLogEntity accountCashLogEntity = new AccountCashLogEntity();
		accountCashLogEntity.setAccountCashId(accountCashEntityDb.getId());
		if(addCashAmount.toString().startsWith("-")) {
			BigDecimal newAddCashAmount = new BigDecimal(addCashAmount.toString().substring(1));
			accountCashLogEntity.setChangeAmount(newAddCashAmount);
			accountCashLogEntity.setOperType(20);
		}else {
			accountCashLogEntity.setOperType(10);
			accountCashLogEntity.setChangeAmount(addCashAmount);
		}
		accountCashLogEntity.setChargeType(30);
		accountCashLogEntity.setCreateTime(new Date());
		accountCashLogEntity.setModifyTime(new Date());
		accountCashLogDao.save(accountCashLogEntity);
		return 0;
	}
	
	public static void main(String[] args) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		BasicNameValuePair outTradeNoParam = new BasicNameValuePair("outTradeNo", "");
		params.add(outTradeNoParam);
		try {
			String body = HttpClientUtil.getPostBodyDataNameValuePair("https://api.wdb007.com/wdb007/charge/refundByOutTradeNo", params);
			System.out.println(body);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
